package roborally.script.conditionalCommand;

import roborally.model.Robot;
import roborally.script.Command;
import roborally.script.Condition;
import roborally.script.ConditionalCommand;
import be.kuleuven.cs.som.annotate.*;
import be.kuleuven.cs.som.taglet.*;

/**
 * @author Joren VERSPEURT
 * @author Mathieu REYMOND
 * @version 3.0
 * 
 * The class representing a While statement in the RoboRally script language.
 */
public class While extends ConditionalCommand {
	
	/**
	 * Create a new If with a given Robot, Condition and 1 Command, which is executed as long as the Condition is true.
	 * @param robot The Robot this While will apply to.
	 * @param condition The Condition that applies to this While.
	 * @param command The Command, which is executed as long as the Condition is true.
	 */
	public While(Robot robot, Condition condition, Command command) {
		super(robot, condition, command);
		running = false;
	}

	/**
	 * If the Condition is true, or the sub-Command was stepped (but not finished), execute the next step of the While's sub-Command.
	 * The While Command will not be set to <code>executed == true</code> as long as the Condition is true.
	 */
	@Override
	public void step() {
		if(condition.isTrue() && !running) {
			setExecuted(false);
			getCommands().get(0).setExecuted(false);
		}
		
		if(condition.isTrue() || running) {
			running = true;
			getCommands().get(0).step();
			if(getCommands().get(0).isExecuted()) {
				running = false;
			}
		}
		else {
			setExecuted(true);
		}
		
	}
	
	/**
	 * The script word for this command.
	 */
	@Override
	public String toString() {
		return "while";
	}
	
	/**
	 * Indicates if the condition was true when needed to be checked, to directly continue in the While loop when the next step is invoked.
	 */
	private boolean running;
}
